package com.ccrfid.rmc6.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5PasswordUtil {
    public static String encodePassword(String rawPass, String salt) {
        try {
            String saltedPass = mergePasswordAndSalt(rawPass, salt);
            byte[] saltedPassBytes = saltedPass.getBytes("UTF-8");

            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] mdBytes = md.digest(saltedPassBytes);

            return toHexString(mdBytes);
        } catch (UnsupportedEncodingException ex) {
            throw new IllegalArgumentException("No such charset [UTF-8]");
        } catch (NoSuchAlgorithmException ex) {
            throw new IllegalArgumentException("No such algorithm [MD5]");
        }
    }

    private static String mergePasswordAndSalt(String password, String salt) {
        if (password == null) {
            return "";
        } else {
            if (salt == null || "".equals(salt)) {
                return password;
            } else {
                return salt + ":" + password;
            }
        }
    }

    public static boolean isPasswordValid(String encPass, String rawPass, String salt) {
        return encPass.toUpperCase().equals(encodePassword(rawPass, salt).toUpperCase());
    }

    private static final char[] hex = "0123456789ABCDEF".toCharArray();

    private static String toHexString(byte[] bytes) {
        if (bytes == null) {
            return null;
        }

        StringBuilder sb = new StringBuilder(bytes.length << 1);
        for (int i = 0; i < bytes.length; ++i) {
            sb.append(hex[(bytes[i] & 0xf0) >> 4])
                    .append(hex[(bytes[i] & 0x0f)]);
        }
        return sb.toString();
    }
}
